package Talk;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @Description:聊天室
 * @Author: 杨淮尊
 * @Date: 2020/4/29
 **/
@ServerEndpoint(value = "/page_room/{username}")
public class WsByTomcat {
    //房间内成员容器
    private static Collection<Session> sessions = Collections.synchronizedCollection(new ArrayList<Session>());

   /**
    * @Param: [session, username]
    * @Return: void
    * @Author: yhz
    * @Date: 2020/4/29 14:15
    */
    @OnOpen
    public void OnOpen(Session session, @PathParam("username") String username) throws IOException {
        sessions.add(session);
    }

  /**
   * @Param: [msg, username]
   * @Return: void
   * @Author: yhz
   * @Date: 2020/4/29 14:16
   */
    @OnMessage
    public void OnMsg(String msg, @PathParam("username") String username) throws IOException {
        sendTextMsg(username + "：\r" + msg);
    }


    /**
     * @Param: [session, username]
     * @Return: void
     * @Author: yhz
     * @Date: 2020/4/29 14:16
     */
    @OnClose
    public void OnClose(Session session, @PathParam("username") String username) throws IOException {
        sessions.remove(session);
    }

     /**
      * @Param: [e]
      * @Return: void
      * @Author: yhz
      * @Date: 2020/4/29 14:16
      */
    @OnError
    public void OnError(Throwable e) {
        e.printStackTrace();
    }

    /**
     * @Param: [msg]
     * @Return: void
     * @Author: yhz
     * @Date: 2020/4/29 14:16
     */
    private void sendTextMsg(String msg) {
        for (Session session : sessions) {
            session.getAsyncRemote().sendText(msg);
        }
    }
}